/**
 * 自定义 请求信息中间件
 */

import { Injectable, NestMiddleware } from '@nestjs/common';
import { NextFunction, Request, Response } from 'express';
import { HttpLogger } from 'src/logger/logger';
@Injectable()
export class HttpRequestMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    next();
    const logFormat: any = {
      httpType: `Request`,
      ip: req.headers?.remoteip
        ? String(req.headers.remoteip)
        : req.ip.split(':').pop(),
      reqUrl: `${req.headers.host}?${req.originalUrl}`,
      reqMethod: req.method,
      httpCode: res.statusCode,
      params: req.params,
      query: req.query,
      body: req.body,
    };
    if (res.statusCode >= 400) {
      HttpLogger.error(JSON.stringify(logFormat));
    } else {
      HttpLogger.access(JSON.stringify(logFormat));
    }
  }
}
